package siyuan.run.nacos.security.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import siyuan.run.nacos.security.service.UserSecurityService;

/**
 * @program: sy
 * @description:
 * @author: SY
 * @create: 2020-12-20 22:18
 **/
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private AuthenticationSuccessHandler successHandler;
    @Autowired
    private AuthenticationFailureHandler failureHandler;

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.antMatcher("/user/**").
                formLogin().usernameParameter("username").passwordParameter("password").loginPage("/user/login").successHandler(
                successHandler).failureHandler(failureHandler)
                .and()
                .authorizeRequests()
                //登录相关
                .antMatchers("/user/login").permitAll()
                .antMatchers("/user/register").permitAll();
        http.logout().permitAll();
        http.cors().and().csrf().ignoringAntMatchers("/user/**");
        http.logout().logoutUrl("/user/logout").permitAll();
    }

    @Bean
    UserDetailsService UserSecurityService() {
        return new UserSecurityService();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(UserSecurityService()).passwordEncoder(new BCryptPasswordEncoder() {
        });
    }
}
